# frozen_string_literal: true

# class for tasks
class Task
  include Mongoid::Document
  include Mongoid::Timestamps
  include Db::Operations
  include Db::Cacheable
  field :title, type: String
  field :body, type: String
  field :status, type: Integer, default: 0 # 0: draft; 1:planned
  field :emergency, type: Integer, default: 1
  field :importance, type: Integer, default: 1
  field :t_id, type: String, default: -> { id.to_s }
  field :deleted, type: Boolean, default: false
  field :point, type: Integer, default: 0
  field :tags, type: Hash, default: {}
  field :level_point
  field :is_mock, type: Boolean, default: false
  scope :valid, -> { where(deleted: false) }

  scope :draft, -> { where(status: 0) }
  scope :planned, -> { where(status: 1) }

  after_create :send_create_msg
  after_update :send_update_msg
  after_destroy :send_destroy_msg

  POINT_DICT = { imp: 3, emgr: 5, intr: 1 }.freeze

  def level_point
    point = 0
    tags.each do |k, v|
      point += v * POINT_DICT[k.to_sym] if POINT_DICT[k.to_sym]
    end
    point
  end

  def add_tag!(tag_name)
    if tags[tag_name]
      tags[tag_name] += 1
    else
      tags[tag_name] = 1
    end
    save!
  end

  def self.pickone
    # redis = Redis.new
    data = create!(title: 'from remote', body: 'what is the hell')
    front_action = { 'namespace': 'task',
                     'mutation': 'addTaskList' }
    redis.publish(:broadcast, front_action.merge!(data.attributes).to_json)
  end

  protected

  def send_create_msg
    front_action = { 'namespace': 'task',
                     'mutation': 'addTaskList' }
    redis.publish(:broadcast, front_action.merge(attributes).to_json)
  end

  def send_update_msg
    front_action = { 'namespace': 'task',
                     'mutation': 'updateTask' }
    redis.publish(:broadcast, front_action.merge(attributes).to_json)
  end

  def send_destroy_msg
    front_action = { 'namespace': 'task',
                     'mutation': 'removeTask' }
    redis.publish(:broadcast, front_action.merge(attributes).to_json)
  end
end
